package cn.touna.jss.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;

/**
 * 3DES加密工具类
 */
public class Des3 {
    // 密钥
    private final static String secretKey = "touna@XFFQDKLMSAPPXX@@#$";

    // 向量
    private final static String iv = "01234567";

    // 加解密统一使用的编码方式
    private final static String encoding = "utf-8";

    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @return
     * @throws Exception
     */
    public static String encode(String plainText) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
        return Base64.encode(encryptData);
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

        byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));

        return new String(decryptData, encoding);
    }

    public static void main(String[] args) throws Exception {
        String encryptText = CommonUtils.urlDecodeUTF8("0%2Fvp1uD3ba%2BLaFXo85EbpvAQa9EACoBDGHf1SO3FyMs4eUz8DRsOG%2FjHC7xi+Bo%2F71hWE%2BhE%2FK%2FodI8rVAk98MJgHW%2FhRXCMtzhVfxw%2FtdhbpZOi7N7UPykds+TbUUuuQx%2BjXWJE2ohYzocvMcXi5TbsVfW8nfh09UhYX0Arprr4A3GX3Z8vW2+RSBilG2EYOVs1lEJAM0RWs%2FgK8B8t75WL9G7rlnAjFSlO9U5vtPlFpVdzz0%2F+aT9omO5FxcEasdWE6bn1G5gjdMxXgLrKe%2FIWw%2Fs8VCqNdGclav1%2FXxCKpk3y+b0vNrGlQb84%2BXi9wr7jH1b1bvx9HYbgjxMqOulr9cQ7ljBJNpRqU3yJ7%2BYk1+L8EyjEFz7WOKxTTLh%2BcSkm7MmVhZ2jWgIcs5%2BDCgEuw2u15URDNBc2Tt6PWn+W%2FHeZg4Csm3etohX45RhtoTlrUHjCP0nN8iGNDhD9YeTLb97Wefa%2B8YGUigb+4vazrDtX6CJaNOOBYOEG4KrEMVNC4z569HIVl01%2FBan%2BA45CNXaOgJ4%2FG4uN+RposmqAtKUq0osP3xjp%2Fs5mwcSUd7LpncJJrxyKGnBz%2FPBRpIpEF3lTnMwTV+YrPANnaCiSxtsBzoIGv6R30MxUKnBoouqbo8lWjWlO6DPPQ0O8Vk2YhtzPeY+R2%2F9OaN465lsJEBQb5iKjoggCqn2yI4jcQ%3D%3D");
        String params = decode(encryptText);
        System.out.println(params);
    }

}
